package chapter.tenth.item66;

public class SerialNumber {
	private static volatile int nextSerialNumber = 0;
	
	//++操作是非原子性的，可以使用AtomicLong替代int
	public static synchronized int generateSerialNumber(){
		return nextSerialNumber++;
	}
	
	/**
	 * generateSerialNumber通过同步控制确保多线程下的互斥
	 * @param args
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread(new Runnable(){
			public void run() {
					System.out.println("Thread1--: "+SerialNumber.generateSerialNumber());
			}
		});
		Thread t2 = new Thread(new Runnable(){
			public void run() {
					System.out.println("Thread2--: "+SerialNumber.generateSerialNumber());
			}
		});
		t1.start();
		t2.start();
		
	}
}
